package server.requesthandler;

import client.request.CreateGroupRequestMessage;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.channel.group.ChannelGroup;
import io.netty.channel.group.DefaultChannelGroup;
import io.netty.util.concurrent.GlobalEventExecutor;
import server.response.CreateGroupResponseMessage;
import util.ChannelUtils;

import java.util.ArrayList;
import java.util.List;

/**
 * @Description 对客户端发出创建群聊请求的响应
 * @author czc
 */
public class CreateGroupRequestHandler extends SimpleChannelInboundHandler<CreateGroupRequestMessage> {
    @Override
    protected void channelRead0(ChannelHandlerContext ctx, CreateGroupRequestMessage msg) throws Exception {
        System.out.println("creategroup 收到请求");
        List<String> userNameList = msg.getUserNameList();
        //创建第二个存放username的list，被邀请的用户可能不在线，successUserName存放在线且成功被邀请的用户id
        List<String> successUserName = new ArrayList<>();
        ChannelGroup channelGroup = new DefaultChannelGroup(GlobalEventExecutor.INSTANCE);
        for(String username : userNameList) {
            //从存储channel，username的类中提取channel
            Channel channel = ChannelUtils.getChannel(username);
            if(channel != null) {
                channelGroup.add(channel);
                successUserName.add(username);
            }
        }
        //将自己的channel添加到ChannelGroup
        channelGroup.add(ctx.channel());
        //将自己的名字添加到list
        successUserName.add(msg.getInitiator());

        ChannelUtils.putChannelGroupId("123123", channelGroup);
        CreateGroupResponseMessage createGroupResponseMessage =
                new CreateGroupResponseMessage(true, 123123, successUserName);
        channelGroup.forEach(ch -> {
            ch.writeAndFlush(createGroupResponseMessage);
        });

        System.out.println("群创建成功, id = [" + createGroupResponseMessage.getGroupId() + "]");
        System.out.println("群里有 " + createGroupResponseMessage.getUserNameList());
        System.out.println("发起人： " + msg.getInitiator());
    }
}